package org.dg.iag.util;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.log4j.Logger;
import org.dg.iag.dao.FeedDAO;

public class ImportThread extends Thread {
	public static ImportThread importThread;
	
	static Logger logger	= Logger.getLogger(ImportThread.class);
	
	public AtomicBoolean stop		= new AtomicBoolean(false);
	
	private List<String> tagsList	= null;
	private Long groupId			= null;
	private TreeSet<String> tagErrorQueue= new TreeSet<String>();
	
	private boolean saveInTempFolder	= true;
	
	public ImportThread(List<String> tagsList, Long groupId) {
		super();
		this.tagsList = tagsList;
		this.groupId = groupId;
		this.tagErrorQueue= new TreeSet<String>();
	}
	
	public ImportThread(List<String> tagsList, Long groupId, boolean saveInTempFolder) {
		super();
		this.tagsList = tagsList;
		this.groupId = groupId;
		this.tagErrorQueue= new TreeSet<String>();
		this.saveInTempFolder	= saveInTempFolder;
	}
	
	public ImportThread(String tag, Long groupId, boolean saveInTempFolder) {
		this.tagsList	= new ArrayList<String>(1);
		this.tagsList.add(tag);
		this.groupId = groupId;
		this.tagErrorQueue= new TreeSet<String>();
		this.saveInTempFolder	= saveInTempFolder;
	}
	
	
	public ImportThread() {
		this.tagsList 	= null;
		this.groupId 	= null;
		this.stop		= new AtomicBoolean(false);
		this.tagErrorQueue= new TreeSet<String>();
	}
	@Override
	public void run () {
		try {
			logger.info("Starting new thread for importing feeds.");
			FeedDAO	dao		= new FeedDAO(this.saveInTempFolder);
			
			if ( this.groupId == null ) {
				dao.storeAllFeeds(this);
			}
			else if ( this.tagsList != null || this.tagsList.size() > 0 ) {
				dao.storeFeeds(tagsList, groupId,tagErrorQueue);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
